/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ua.yandex.sumofseries.utilconcurrent;

import java.lang.reflect.Array;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 *
 * @author vlad
 */
public class TaskManager {

    public static double execute(Range[] ranges) {
        if (ranges == null) {
            throw new NullPointerException("Null array(s) as argument");
        }
        if (ranges.length == 0) {
            throw new IllegalArgumentException("Zero ranges size");
        }
        double sum = 0;
        ExecutorService executor = Executors.newFixedThreadPool(ranges.length);
        Future<Double>[] results
                = (Future<Double>[]) Array.newInstance(Future.class,
                        ranges.length);
        for (int i = 0; i < ranges.length; i++) {
            results[i] = executor.submit(new CalcSmallInterval(
                    ranges[i].getStart(), ranges[i].getEnd()));
        }
        for (Future<Double> res : results) {
            try {
                sum += res.get();
            } catch (InterruptedException | ExecutionException e) {
                System.out.println(e.getMessage());
            }

        }
        return 0;
    }
}
